﻿using System.Collections.Generic;
using System.Linq;

namespace YawetagLib.Data
{
    public abstract class CrudRepository<TEntity> : BaseRepository, ICrudRepository<TEntity> where TEntity : class
    {
        protected CrudRepository(IDataContext dataContext) 
            : base(dataContext)
        {
        }

        public virtual TEntity Get(int entityID)
        {
            return DataSource.Get(entityID);
        }

        public virtual TEntity GetOrDefault(int entityID)
        {
            return DataSource.GetOrDefault(entityID);
        }

        public virtual IList<TEntity> GetAll()
        {
            return GetOrderedSet(DataSource.GetAll()).ToList();
        }

        public virtual void Insert(TEntity entity)
        {
            DataSource.Insert(entity);
            
            DataContext.SubmitChanges();
        }

        public virtual void Update(TEntity entity)
        {
            DataSource.Update(entity);

            DataContext.SubmitChanges();
        }

        public virtual void Delete(TEntity entity)
        {
            DataSource.Delete(entity);

            DataContext.SubmitChanges();
        }

        protected virtual IEnumerable<TEntity> GetOrderedSet(IEnumerable<TEntity> entitySet)
        {
            return entitySet;
        }

        protected IDataSource<TEntity> DataSource { get; set; }

        protected new ICrudDataContext DataContext
        {
            get { return (ICrudDataContext)base.DataContext; }
        }
    }
}
